<!DOCTYPE HTML>
<html>

  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <title>Butterfly</title>
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0px; padding: 0px }
      #map { width:100%; height:90% }
      button {width:100%; height:10%; display:block }
    </style>
  </head>

  <body>

  <script type="text/javascript" charset="utf-8" src="phonegap-0.9.2.js"></script>      
  <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
  <script type="text/javascript" src="base64.js"></script>

  <script type="text/javascript" charset="utf-8">
  
  		var STORE_URL = 'http://78.47.21.51:5984/butterfly/';
  		var map = null;
  		var pos = null;
  		var posMarker = null;
//  		var pictures = new Array();
  		
        var currentPositionSuccess = function(position) { // Grab coordinates object from the Position object passed into success callback.
        	pos = position;
        	var coords = position.coords;
//        	alert(coords.latitude + ", " + coords.longitude);
            var latlng = new google.maps.LatLng(coords.latitude, coords.longitude);
            var myOptions = {
              zoom: 17,
              center: latlng,
              mapTypeId: google.maps.MapTypeId.HYBRID
            };
            map = new google.maps.Map(document.getElementById("map"), myOptions);
            var image = 'butterfly.gif';
            posMarker = new google.maps.Marker({
                position: latlng,
                map: map,
                icon: image
            });
            var options = { frequency: 1000, maximumAge: 3000, timeout: 5000, enableHighAccuracy: true };
            navigator.geolocation.watchPosition(watchPositionSuccess, positionError, options);
        };      
  		
        var watchPositionSuccess = function(position) {
        	pos = position;
  			var coords = position.coords;
            var latlng = new google.maps.LatLng(coords.latitude, coords.longitude);
            posMarker.setPosition(latlng);
            var bounds = map.getBounds();
            if (!bounds.contains(latlng)) {
            	map.panTo(latlng);
            }
  		}
        
        var positionError = function(e) {
        	alert('Can\'t retrieve position.\nError: ' + e);
        };
        
        var cameraSuccess = function(imageData) {
//        	pictures.push({lat:pos.coords.latitude, lng:pos.coords.longitude, img:imageData});
alert(imageData);
        	if (confirm('Pic taken! Send?')) {
        		var req = new XMLHttpRequest();
        		var method = 'put';
        		var id = Math.floor(Math.random() * 1000000);
        		var url = STORE_URL + id;
        		req.onreadystatechange = function() {
        			if (req.readyState == 4) {
            			if (req.status != 201) {
            			     alert('The picture could not be transmitted.\nStatus: ' + req.statusText + ' (' + req.status + ').');
            			     return;
            			}
        				rev = JSON.parse( req.responseText ).rev;
        				var attachment_req  = new XMLHttpRequest();
        				var url = STORE_URL + id + "/img.jpg?rev=" + rev;
        				attachment_req.open('put', url, true);
        				attachment_req.onreadystatechange= function() {
        					if (attachment_req.readyState != 4) {
                					return;
            			    }
        				    if (attachment_req.status != 201) {
            				  alert('Attachment could not be sent.');
            				  return;
        				    }
        		            var latlng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
        		            var image = 'camera_icon.png';
        		            var posMarker = new google.maps.Marker({
        		                position: latlng,
        		                map: map,
        		                icon: image
        		            });
            			};
            			attachment_req.setRequestHeader('Content-Type', 'image/jpeg');
            			attachment_req.setRequestHeader('Content-Transfer-Encoding', 'base64');
        				attachment_req.send(imageData);
        			}
        		}
        		req.open(method, url, true);
        		req.send(JSON.stringify({lat:pos.coords.latitude, lng:pos.coords.longitude}));
        	}
        }
        
        var cameraError = function(message) {
        	alert('Can\'t take pic.\nError: ' + message);
        }
        
        var takePic = function() {
        	var options = { quality:50 };
        	var pic = navigator.camera.getPicture(cameraSuccess, cameraError, options);
        }
        
        document.addEventListener("deviceready", function() {
            alert('now initialized');
            pos = { coords : { "latitude" : 12.3, "longitude" : 23.3} };
            cameraSuccess("/9j/4AAQSkZJRgABAQEASABIAAD/\
2wBDAAYEBAQFBAYFBQYJBgUGCQsIBgYICwwKCgsKCgwQDAwMDAwMEAwODxAPDgwTExQUExM\
cGxsbHCAgICAgICAgICD/2wBDAQcHBw0MDRgQEBgaFREVGiAgICAgICAgICAgICAgICA\
gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICD/wAARCAFKABsDAREAAhEBAx\
EB/8QAGQABAQEBAQEAAAAAAAAAAAAAAAECBAMI/8QAFxABAQEBAAAAAAAAAAAAAAAA\
ABESE//EABQBAQAAAAAAAAAAAAAAAAAAAAD/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/\
9oADAMBAAIRAxEAPwD6pAAAAAAABAAAASgUCgUEAAABAAAASgUCgUAAAAGQAAAKBQ\
KBQQAAAEAAABAAAASgUCgUEAAABAAAASgUCgUEAAABAAAAQAAAEoFAoFBAAAAQAAA\
EoFAoFAAAABkAAACgUCgUEAAABAAAAQAAAEoFAoFBAAAAQAAAEoFAoFBAAAAQAAAEAA\
AB47A2BsDYOboB0A6AdAc3QDoB0A6A5tgbA2BsGQAAAf/Z");
        	//navigator.geolocation.getCurrentPosition(currentPositionSuccess, positionError);
	    }, true);
  </script>
  
  <div id="map"></div>
  <button id="picButton" onclick="takePic();">Take Pic!</button>
  </body>

</html>